<template>
  <div class="customs_goods_box">
    <el-table
      :data="tableData"
      border
      :height="tableHeight"
      show-summary
      :summary-method="getSummaries"
      @header-click="tableHeardClick"
      style="width: 100%">
      <el-table-column
          v-for="(item, index) in tableHeaderData"
          :key="index"
          :index="index"
          :align="item.align ? item.align : 'center'"
          :prop="item.prop"
          :class-name="item.className"
          :show-overflow-tooltip="true"
          :label="item.label"
          :width="item.width">
          <!-- 表头 -->
          <template slot="header" slot-scope="scope">
            <template v-if="item.toolHeadrTip">
              <el-tooltip class="item" effect="dark" :content="item.toolHeadrTip" placement="top" :enterable="false">
                <div :class="item.class">{{item.label}}</div>
              </el-tooltip>
            </template>
            <div v-else>{{item.label}}</div>
          </template>
          <!-- 表体 -->
          <template slot-scope="scope">
            <!-- 输入行 -->
            <div v-if="item.type === 'edit'" class="tb-edit">
              <template v-if="item.tooltip">
                <el-tooltip class="item" effect="dark" :content="item.tooltip" placement="top" :enterable="false">
                  <el-input :ref="scope.$index" :index="index" :column="JSON.stringify(item)"
                  @keyup.native="validateCounts(scope.$index, index, scope, $event, item)"
                  @focus="(e) => { e.currentTarget.select() }"
                  :placeholder="item.placeholder? item.placeholder: ' '"
                  :disabled="item.disabled"
                  v-model.trim="scope.row[item.prop]" >
                  </el-input>
                </el-tooltip>
              </template>
              <template v-else>
                <el-input :ref="scope.$index" :index="index" :column="JSON.stringify(item)"
                @keyup.native="validateCounts(scope.$index, index, scope, $event, item)"
                @blur="tableInputBlur(scope, item)"
                @focus="(e) => { e.currentTarget.select() }"
                :placeholder="item.placeholder? item.placeholder: ' '"
                :disabled="item.disabled"
                :type="item.inputType? item.inputType: 'text'"
                v-model.trim="scope.row[item.prop]" >
                </el-input>
              </template>
            </div>
            <!-- 下拉选项 -->
            <div v-else-if="item.type === 'select'">
              <!-- 远程搜索 -->
              <!-- :remote-method="(query)=>{ remoteMethod(query, scope, item, ['code']) }" -->
              <template v-if="item.isSearch">
                <el-select
                :ref="scope.$index"
                :index="index" 
                :column="JSON.stringify(item)"
                @keyup.native="validateCounts(scope.$index, index, scope, $event, item)"
                @visible-change="setSelectOptions($event, scope, index, item)"
                @focus="setSelectFocus"
                filterable
                :remote="true"
                :default-first-option="true"
                class="asbtm" 
                :disabled="item.disabled"
                v-model.lazy="scope.row[item.prop]"
                placeholder=""
                v-icon-hide>
                  <!-- 通用表格选项 -->
                  <template>
                    <el-option v-if="selectItem.id == scope.row[item.prop]" v-for="(selectItem) in selectQueryAll[item.optionKey]" :key="String(selectItem.id)" :label="`${selectItem.codeV2}-${selectItem.name}`" :value="String(selectItem.id)"></el-option>
                    <el-option v-if="selectItem.id != scope.row[item.prop]" v-for="(selectItem) in item.option" :key="String(selectItem.id)" :label="`${selectItem.codeV2}-${selectItem.name}`" :value="String(selectItem.id)"></el-option>
                  </template>
                </el-select>
              </template>
              <!-- 非远程搜索 -->
              <template v-if="!item.isSearch">
                <el-select
                :ref="scope.$index"
                :index="index" 
                :column="JSON.stringify(item)"
                @keyup.native="validateCounts(scope.$index, index, scope, $event, item)"
                @visible-change="setSelectOptions($event, scope, index, item)"
                @focus="setSelectFocus"
                filterable
                :remote="true"
                :default-first-option="true"
                class="asbtm" 
                :disabled="item.disabled"
                v-model.lazy="scope.row[item.prop]"
                placeholder=""
                v-icon-hide>
                  <!-- 通用表格选项 -->
                  <template v-if="!item.isRowOptions && item.optionKey">
                    <el-option v-if="selectItem.id == scope.row[item.prop]" v-for="(selectItem) in selectQueryAll[item.optionKey]" :key="String(selectItem.id)" :label="`${selectItem.codeV2}-${selectItem.name}`" :value="String(selectItem.id)"></el-option>
                    <el-option v-if="selectItem.id != scope.row[item.prop]" v-for="(selectItem) in item.option" :key="String(selectItem.id)" :label="`${selectItem.codeV2}-${selectItem.name}`" :value="String(selectItem.id)"></el-option>
                  </template>
                  <!-- 表格内容自带选项 -->
                  <template v-else-if="item.isRowOptions">
                    <el-option v-for="(selectItem) in (scope.row[item.isRowOptions] !== null ? scope.row[item.isRowOptions] : [])" :key="String(selectItem.id)" :label="`${selectItem.code}-${selectItem.name}`" :value="String(selectItem.id)"></el-option>
                  </template>
                  <!-- 固定参数选项 -->
                  <template v-else>
                    <el-option v-for="(selectItem) in item.option" :key="String(selectItem.id)" :label="`${selectItem.code}-${selectItem.name}`" :value="String(selectItem.id)"></el-option>
                  </template>
                </el-select>
              </template>
            </div>
            <!-- 索引 -->
            <div v-else-if="item.type === 'index'">{{scope.$index+1}}</div>
            <!-- 添加 -->
            <div v-else-if="item.type === 'add'" class="cus-p">
              <div @click="removerRow(scope)">-</div>
            </div>
            <div v-else-if="item.type === 'move'">
              <el-tooltip class="item" effect="dark" content="上移" placement="top" :enterable="false">
                <i class="el-icon-top cus-p hoverColor" @click="clickUp(scope.$index)"></i>
              </el-tooltip>
              <el-tooltip class="item" effect="dark" content="下移" placement="top" :enterable="false">
                <i class="el-icon-bottom cus-p hoverColor" @click="clickDown(scope.$index)"></i>
              </el-tooltip>
              <el-tooltip class="item" effect="dark" content="复制" placement="top" :enterable="false">
                <i class="el-icon-copy-document cus-p hoverColor" @click="copyRow(scope)"></i>
              </el-tooltip>
            </div>
            <!-- 选择商品要素 -->
            <div v-else-if="item.type === 'goodsElements'" style="min-height:20px;" class="cus-p" @click="openGoodsElements(scope, 'click')">{{scope.row[item.prop]}}</div>
            <div v-else>{{scope.row[item.prop]}}</div>
          </template>
        </el-table-column>
    </el-table>

    <!-- 商品选择 -->
    <select-goods v-if="dialogGoodsVisible" :dialogGoodsVisible="dialogGoodsVisible" :closeGoods="closeGoods" :goodsParams="goodsParams"></select-goods>

    <!-- 商品要素选择 -->
    <el-dialog class="goods_elements" title="商品申报要素" width="760px" :visible.sync="dialogGoodsElementsVisible" :close-on-click-modal="false">
      <el-table :data="goodsElementsData" border>
        <el-table-column label="序号" width="70px" align="center">
          <template slot-scope="scope">
            {{scope.$index + 1}}
          </template>
        </el-table-column>
        <el-table-column label="申报要素名称" width="225px" prop="name" align="center">
          <template slot-scope="scope">
            <div :style="{color: scope.row.required ? 'red': '#000'}">{{scope.row['name']}}</div>
          </template>
        </el-table-column>
        <el-table-column label="申报要素内容" width="374px" align="center">
          <template slot-scope="scope">
            <template v-if="scope.row.type === 'select'">
              <el-select
              :ref="scope.row['key']"
              style="width:100%;"
              @focus="setSelectFocus"
              @keyup.native="validateGoodsElements(scope, $event)"
              filterable
              :default-first-option="true"
              :disabled="scope.row.disabled"
              v-model.lazy="scope.row['value']"
              placeholder=""
              v-icon-hide>
                  <el-option v-for="selectItem in scope.row.option" :key="selectItem.id" :label="selectItem.codeV2 || selectItem.codeV2 === 0 ? `${selectItem.codeV2} - ${selectItem.name}` : selectItem.name" :value="selectItem.id"></el-option>
              </el-select>
            </template>
            <template v-else-if="scope.row.type === 'edit'">
               <el-input @focus="(e) => { e.currentTarget.select() }" @keyup.native="validateGoodsElements(scope, $event)" :ref="scope.row['key']" placeholder=" " :disabled="scope.row.disabled" :maxlength="50" v-model.trim="scope.row['value']" ></el-input>
            </template>
          </template>
        </el-table-column>
        <el-table-column label="历史" width="50px" align="center">
          <template slot-scope="scope">
            <div class="tc"><i class="el-icon-time"></i></div>
          </template>
        </el-table-column>
      </el-table>
      <div class="clearfix mt-10">
        <div class="l redcolor">*红色申报要素为必填项，点击每项右侧按钮可查看历史申报(放行)数据</div>
        <el-button class="r" type="primary" size="small" @click="onSubmitGoodsElements">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { mapState,mapMutations } from 'vuex';
import selectGoods from '@/components/selectGoods/index';
import { searchGoods } from '@/axios/api';
import idb from '@/utils/idb';
import { setObjectKeyString } from '@/utils/util';

var viewer = null;
export default {
  name: 'editTable',
  data () {
    return {
      selectQueryAll: {},
      selectMax: 20,
      fixedNumber: 3,
      // 商品选择
      dialogGoodsVisible: false,
      goodsParams: {},
      // 商品要素选择
      dialogGoodsElementsVisible: false,
      goodsElementsData: [],
    }
  },
  props: {
    // 表头数据
    tableHeaderData: {
      type: Array,
      default: (e) => {
        return []
      }
    },
    tableData: {
      type: Array,
      default: (e) => {
        return []
      }
    },
    tableHeight: {
      type: Number,
      default: (e) => {
        return ''
      }
    },
    tableKeydown: {
      type: Function,
      default: () => {
        return ''
      }
    },
    tableType: { // 表格标识
      type: String,
      default: () => {
        return ''
      }
    }
  },
  computed:{
    ...mapState([])
  },
  watch: {
  },
  components: {
    selectGoods
  },
  mounted() {
  },
  created(){
    this.initIdb()
  },
  methods: {
    ...mapMutations([]),
    /**
     * @method 初始化数据库
     */
    initIdb() {
      let self = this
      // 初始化idb数据库
      idb.init('baoguange', {
        query: {
          selectCommonAll: true
        }
      }).then(res => {
        // let options = {}
        res.forEach(item => {
          if (item.id === 'createTime') {
            return
          }
          self.$set(self.selectQueryAll, item.id, item.data)
        })
        // self.selectQueryAll = Object.assign(self.selectQueryAll, options)
        // self.commonParams = Object.assign(self.commonParams ,JSON.parse(JSON.stringify(self.selectQueryAll)))
      })
    },
    /**
     * @method 表头点击
     */
    tableHeardClick(column, event) {
      const self = this
      // 重置为第一项数据的prop
      let resetProps = ['originCountryId', 'destinationCountryId', 'districtCodeId', 'csbaseCurrencyId', 'csbaseExempId']
      if (column.label === '[ + ]') {
        // 添加
        if(self.tableType === 'goods') {
          let parentData = self.$parent.$parent.$parent
          self.$set(self.tableData, self.tableData.length, {
            originCountryId: '41',
            csbaseCurrencyId: '22',
            dealQuantity: '00.00',
            legalQuantity: '00.00',
            twoQuantity: '00.00',
            containerCount: 0,
            destinationCountryId: parentData.formData.csbaseCountryId ? parentData.formData.csbaseCountryId : self.tableData[self.tableData.length-1].destinationCountryId,
            districtCodeId: self.tableData[self.tableData.length-1] ? self.tableData[self.tableData.length-1].districtCodeId : '',
            csbaseExempId: '2374',
            nw: 0,
            gw: 0,
          })
        } else {
          self.$set(self.tableData, self.tableData.length, {})
        }
      } else if (column.property === 'nw' && self.tableData.length > 0) {
        // 计算
        self.tableData.forEach((item, index) => {
          // 计算千克单位 306
          let isMake = false
          item.containerCount = item.containerCount || 0
          item.nw = item.nw || 0
          item.gw = item.gw || 0
          if (item.dealUnitId == '306' && item.dealQuantity != 0 && item.dealQuantity) {
            isMake = item.dealQuantity
          }
          if (item.legalUnitId == '306' && item.legalQuantity != 0 && item.legalQuantity && !isMake ) {
            isMake = item.legalQuantity
          }
          if (item.twoUnitId == '306' && item.twoQuantity != 0 && item.twoQuantity && !isMake) {
            isMake = item.twoQuantity
          }

          if (!isMake) {
            // 没有千克单位
            if (!item.containerCount || !item.nw) {
              return
            }
            item.gw = parseFloat(item.nw) + parseFloat(item.containerCount)
          } else {
            // 有千克单位
            item.nw = isMake
            item.gw = parseFloat(item.nw) + parseFloat(item.containerCount)
          }
          self.$nextTick(() => {
            self.$set(self.tableData, index, item)
          })
        })
      } else if (resetProps.findIndex(item => { return item === column.property}) !== -1 && self.tableData.length > 0) {
        // 设置点击表头修改数据为第一项的值
        if (!self.tableData[0][column.property]) {
          return
        }
        self.tableData.forEach((item, index) => {
          if (index !== 0) {
            self.$set(self.tableData[index], column.property, self.tableData[0][column.property])
          }
        })
      }
    },
    /**
     * @method 删除当前行
     */
    removerRow(scope) {
      // 存在商品数据二次确认
      if (scope.row.id) {
        this.$confirm('是否删除当前行数据?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.tableData.splice(scope.$index,1); 
        }).catch(() => {})
      } else {
        this.tableData.splice(scope.$index,1); 
      }
    },
    /**
     * @method 复制行
     */
    copyRow(scope){
      let item = JSON.parse(JSON.stringify(this.tableData[scope.$index]))
      item.checkedcode = false
      this.tableData.push(item)
    },
    //点击上移
    clickUp(index){
      if (index === 0) {
        return
      }
     this.swapArray(this.tableData, index-1, index);
    },
    //点击下移
    clickDown(index){
      if (this.tableData.length-1 === index) {
        return
      }
     this.swapArray(this.tableData, index, index+1);
    },
    //数组元素互换位置
    swapArray(arr, index1, index2) {
     arr[index1] = arr.splice(index2, 1, arr[index1])[0];
     return arr;
    },
    // 输入框回车事件
    validateCounts(row, index, scope, e ,item) {
      const val = e.target.value;
      let self = this
      var keyCode = e.keyCode || e.which || e.charCode;
      // 选择商品不触发
      if (self.dialogGoodsVisible) {
        return
      }
      if (keyCode === 40 && row === self.tableData.length -1 && item.type !== 'select') {
        // 最后一行按下键复制
        this.copyRow(scope)
        this.$nextTick(() => {
          this.$refs[row+1][0].focus()
        })
        return
      }
      if (keyCode !== 13 && scope.column.property === 'code') {
        this.tableData[row].checkedcode = true
      } else if(keyCode=== 13) {
        let tableRow = row
        let inputIndex = 0
        this.goodsParams.tableRow = row
        // 选择商品
        if (scope.column.label === '商品编码' && (this.tableData[tableRow].checkedcode || val === '')) {
          if (Number(val) && val.length === 10 && !scope.row.id) {
            // 十位编码
            let jsonData = {
                makeType: 1,
                code: val,
                name: '',
                page: 1,
                limit: 99
            }
            searchGoods(jsonData).then(res => {
                if (res.code === 0 && res.data.length === 1) {
                  self.closeGoods(res.data[0])
                } else {
                  this.dialogGoodsVisible = true
                  this.goodsParams.code = val
                }
            })
            return
          }
          this.dialogGoodsVisible = true
          this.goodsParams.code = val
          return
        } else if (scope.column.property === 'name') {
          this.openGoodsElements(scope)
          return
        } else if (scope.column.property === 'nw') {
          if (this.tableData.length-1 === tableRow){
            this.tableData.push({})
          }
          this.$nextTick(() => {
            this.$refs[row+1][0].focus()
          })
          return
        }
        Object.keys(this.$refs).forEach((key, indexKey) => {
          let item = this.$refs[key]
          if (key == tableRow) {
            // 当前行
            item.forEach((input, l) => {
              // 当前input
              if (input.$attrs.index === index) {
                input.blur()
                // 记录下一个索引
                inputIndex = (l+1)
                // 如果有下一个 && 下一个状态不是禁用
                if (item[inputIndex] && !item[inputIndex].disabled) {
                  item[inputIndex].focus()
                } else {
                  let netxFlag = false
                  for(let nextIndex = inputIndex; item.length > nextIndex; nextIndex++) {
                    //查询当前行下一个可编辑input
                    if(!item[nextIndex].disabled) {
                      item[nextIndex].focus()
                      netxFlag = true
                      break
                    }
                  }
                  if (!netxFlag) {
                    // 没有找到
                    let nextItem = self.$refs[Object.keys(self.$refs)[indexKey+1]]
                    if (!nextItem) {
                      return
                    }
                    for(let i = 0; nextItem.length > i; i++) {
                      //查询下一行可编辑input的第一个
                      if(!nextItem[i].disabled) {
                        nextItem[i].focus()
                        break
                      }
                    }
                  }
                }
              }
            })
          }
        });
      } else if (keyCode !== 38 && keyCode !== 40){
        self.$nextTick(() => {
          if ($(e.target).val() == '') {
            self.$set(self.tableData[row], scope.column.property, '')
          }
        })
        // 非上下键回车 搜索条目
        if (item.option) {
          self.$nextTick(() => {
            self.remoteMethod(val, scope, item, ['code', 'codeV2', 'name'])
          })
        }
      }
      // 键盘按下事件调用
      this.$nextTick(() => {
        this.tableKeydown({
          keyCode,
          row,
          index,
          scope,
          e
        })
      })
    },
    /**
     * 远程搜索下拉选项
     */
    remoteMethod(query, scope, item, keys) {
      let self = this
      keys = keys || []
      let arr = []
      console.log(query)
      if (query !== '') {
        arr = self.selectQueryAll[item.optionKey].filter(ferItem => {
          // 全匹配键存在 添加默认
          for(let i=0 ; keys.length > i ; i++) {
            let key = keys[i]
            if (ferItem[key] && ferItem[key].toLowerCase().indexOf(query.toLowerCase()) > -1) {
              return ferItem
            }
          }
        });
        if (arr.length > self.selectMax) {
          arr = arr.slice(0, self.selectMax)
        } else if (arr.length === 0) {
          arr = item.searchData.slice(0, self.selectMax);
        }
      } else {
        if (item.searchData) {
          arr = item.searchData.slice(0, self.selectMax);
        }
      }
      self.$nextTick(() => {
        item.option = arr
      })
    },
    // 下拉框出现隐藏
    setSelectOptions(value, scope, index, item) {
      let tableRowKey = item.prop
      let tableRowIndex = scope.$index
      let optionKey = item.optionKey
      let val = scope.row[item.prop]
      // 出现时赋值 隐藏后清空dom
      if (item.isRowOptions || !this.selectQueryAll[optionKey]) {
        return
      }
      let option = []
      this.$set(this.tableHeaderData[index], 'option', [])
      let data = ''
      this.selectQueryAll[optionKey].forEach(item => {
        if (option.length < this.selectMax) {
          option.push(item)
        }
        // 查询出当前的数据
        if (val == item.id) {
          data = item
        }
      })
      if (value) { // 打开显示
        let flag =  option.findIndex(item => item.id == val)
        if (flag == -1 && data) {
          option.unshift(data)
        }
      }
      this.$nextTick(() => {
        this.$set(this.tableHeaderData[index], 'option', option)
      })
    },
    /**
     * @method 表格输入框失焦事件
     */
    tableInputBlur(scope, item) {
      let value = scope.row[item.prop]
      switch(item.prop) {
        // 单价
        case 'dealPrice':
          if (scope.row['dealQuantity']) {
            let value = parseFloat(Number(scope.row['dealQuantity']) * Number(scope.row['dealPrice'])).toFixed(this.fixedNumber)
            this.$set(this.tableData[scope.$index], 'dealTotalMoney', value )
          }
        break;
        // 总价
        case 'dealTotalMoney':
          if (scope.row['dealQuantity']) {
            let value = parseFloat(Number(scope.row['dealTotalMoney'])/Number(scope.row['dealQuantity'])).toFixed(this.fixedNumber)
            this.$set(this.tableData[scope.$index], 'dealPrice', value )
          }
        break;
      }
    },
    setSelectFocus(e) {
      let inputEl = $(e.srcElement)
      this.$nextTick(()=>{
        inputEl.val(inputEl.attr('placeholder'))
        inputEl.select();
      })
    },
    /**
     * @method 关闭选择商品
     */
    closeGoods(obj) {
      let resetKeys = ['dealQuantity', 'legalQuantity', 'twoQuantity', 'dealPrice', 'dealTotalMoney', 'containerCount', 'gw', 'nw']
      let nowSetKeys = ['originCountryId', 'csbaseCurrencyId', 'csbaseExempId', 'destinationCountryId', 'districtCodeId']
      if (obj) {
        resetKeys.forEach((key) => {
          obj[key] = ''
        })
        nowSetKeys.forEach((key) => {
          obj[key] = this.tableData[this.goodsParams.tableRow][key]
        })
        obj = setObjectKeyString(obj)
        obj.checkedcode = false
        if (obj.goodsCiqs === null || !obj.goodsCiqs) {
          obj.goodsCiqs = []
        }
        this.$set(this.tableData, this.goodsParams.tableRow, obj)
        // 设置初始单位
        this.tableHeaderData.forEach((item, index) => {
          if (item.option) {
            item.option = item.option.filter(filterItem => {
              return filterItem.id != obj[item.prop]
            })
          }
          // 不存在数据
          if (!obj[item.prop]) {
            return
          }
          if (item.prop === 'originCountryId' && obj.originCountry) {
            item.option.push(obj.originCountry)
          } else if (item.prop === 'destinationCountryId' && obj.destinationCountry) {
            item.option.push(obj.destinationCountry)
          } else if (item.prop === 'csbaseCurrencyId' && obj.currency) {
            item.option.push(obj.currency)
          } else if (item.prop === 'csbaseExempId' && obj.exem) {
            item.option.push(obj.exem)
          } else if (item.prop === 'dealUnitId' && obj.dealUnit) {
            item.option.push(obj.dealUnit)
          } else if (item.prop === 'twoUnitId' && obj.twoUnit) {
            item.option.push(obj.twoUnit)
          } else if (item.prop === 'legalUnitId' && obj.legalUnit) {
            item.option.push(obj.legalUnit)
          }
        })
        // 设置初始数据
        if (obj.unitOne) {
          obj.legalUnitId = obj.unitOne.id
          obj.dealUnitId = obj.unitOne.id
        }
        if (obj.unitTwo) {
          obj.twoUnitId = obj.unitTwo.id
        }
      }
      this.dialogGoodsVisible = false
      this.$refs[this.goodsParams.tableRow][0].focus()
    },
    /**
     * @method 打开商品要素
     */
    openGoodsElements(scope, type) {
      // 记录当前打开索引
      this.goodsParams.tableRow = scope.$index
      // 设置值
      if (!scope.row.applyStand) {
        this.$message({
          message: '请选择商品!',
          type: 'warning'
        });
        return
      }
      let sp1List = [
        {id: '0',codeV2:0, name:'无品牌'},
        {id: '1',codeV2:1, name:'境内自主品牌'},
        {id: '2',codeV2:2, name:'境内收购品牌'},
        {id: '3',codeV2:3, name:'境外品牌（贴牌生产）'},
        {id: '4',codeV2:4, name:'境外品牌（其他）'}
      ];
      let sp2List = [
        {id: '0',codeV2:0, name:'出口货物在最终目的国（地区）不享受优惠关税'},
        {id: '1',codeV2:1, name:'出口货物在最终目的国（地区）享受优惠关税'},
        {id: '2',codeV2:2, name:'出口货物不能确定在最终目的国（地区）享受优惠关税'},
        {id: '3',codeV2:3, name:'不适用于进口报关单'}
      ];
      let headerNames = scope.row.applyStand ? scope.row.applyStand.split(';') : []
      let values = scope.row.specs ? scope.row.specs.split('|') : []
      if (headerNames[0] === '1.品名') {
        headerNames.splice(0, 1)
      }
      this.goodsElementsData = []
      let elements = []
      // 设置申报要素表格
      headerNames.forEach((name, index) => {
        let lableName = name.split('.')[1]
        if (lableName === '品牌类型') {
          elements.push({
            name:'品牌类型', key: 'sp1', value: '0', type: 'select', required: true, option: sp1List
          })
        } else if (lableName === '出口享惠情况') {
          elements.push({
            name:'出口享惠情况', key: 'sp2', value: '0', type: 'select', required: true, option: sp2List
          })
        } else {
          let required = true
          if (lableName === 'GTIN' || lableName === 'CAS' || lableName === '其他') {
            required = false
          }
          elements.push({
            name: lableName, key: `value_${index+1}`, value: '', type: 'edit', required: required 
          })
        }
      })
      // 添加其他项
      elements.push({
        name: '其他', key: `value_${elements.length + 1}`, value: '', type: 'edit', required: false 
      })
      values.forEach((value, index) => {
        if (elements[index]) {
          elements[index].value = value
        }
      })
      this.goodsElementsData = elements
      this.dialogGoodsElementsVisible = true
      if (type !== 'click') {
        this.$nextTick(() => {
          this.$refs['sp1'].focus()
        })
      }
    },
    /**
     * @method 商品要素选择
     */
    onSubmitGoodsElements() {
      let jsonData = {
        values: []
      }
      let verify = false
      for (let i=0; i< this.goodsElementsData.length; i++) {
        let item = this.goodsElementsData[i]
        jsonData[item.key] = item.value
        jsonData.values.push(item.value)
        if (item.required && !item.value) {
          verify = true
          this.$message({
            message: `请填写第${i+1}项 - 申报要素${item.name}`,
            type: 'warning'
          });
          return
        }
        if (item.name === 'GTIN' && item.value.length !== 8 && item.value.length !== 12 && item.value.length !== 13 && item.value !== '') {
          this.$message({
            message: 'GTIN长度必须为13、12、8位',
            type: 'warning'
          });
          this.$refs[item.key].focus()
          verify = true
          return
        }
      }
      if (verify) {
        return
      }
      this.$set(this.tableData[this.goodsParams.tableRow], 'specs', jsonData.values.join('|'))
      this.dialogGoodsElementsVisible = false
      this.$refs[this.goodsParams.tableRow][3].focus()
    },
    // 商品要素切换
    validateGoodsElements(scope, e) {
      const self = this
      let required = scope.row.required
      let value = scope.row.value
      var keyCode = e.keyCode || e.which || e.charCode;

      if (keyCode !== 38 && keyCode !== 40 && keyCode !== 13){
        self.$nextTick(() => {
          if ($(e.target).val() == '') {
            self.$set(self.goodsElementsData[scope.$index], 'value', '')
          }
        })
      }

      if (keyCode !== 13) {
        return
      }

      self.$refs[scope.row.key].blur()
      if (self.goodsElementsData[scope.$index + 1]) {
        // 有下一个 并且当前必填项没值
        if (required && !value) {
          self.$nextTick(() => {
            self.$refs[scope.row.key].focus()
          })
          return
        }
        self.$refs[self.goodsElementsData[scope.$index + 1].key].focus()
      } else {
        self.onSubmitGoodsElements()
      }
    },
    /**
     * @method 合计
     */
    getSummaries(param) {
      const { columns, data } = param;
      const sums = [];
      let totals = [];
      this.tableHeaderData.forEach((item) => {
        if (item.isTotal) {
          totals.push(item.prop)
        }
      })
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = '合计';
          return;
        }
        if (!column.property) {
          sums[index] = ''
          return
        }
        if (totals.indexOf(column.property) === -1) {
          sums[index] = ''
          return
        }
        const values = data.map(item => Number(item[column.property]));
        if (!values.every(value => isNaN(value))) {
          sums[index] = values.reduce((prev, curr) => {
            const value = Number(curr);
            if (!isNaN(value)) {
              return prev + curr;
            } else {
              return prev + 0;
            }
          }, 0);
          // sums[index] += ' 元';
        } else {
          sums[index] = '0';
        }
      });
      return sums;
    }
  }
};
</script>

<style lang="scss">
@import "./index.scss";
</style>